import {getOneParValue} from "@/api/dormOneBuildingOneFloor/system";
import { onUnmounted } from "vue";

let echarts = require('echarts/lib/echarts')
let elementResizeDetectorMaker = require("element-resize-detector")
let nodeArrEx = [];
let objInfo = [];
let currentCode = '';
let currenTip = '';
let isReadyData = true;

// 10秒后清空,需要重新获取数据
let timeout = setInterval(() => {
  currentCode = '';
}, 10 * 1000);

// 保持单节点展示
const resetNode = (chartDom, currentEx, index) => {
  const curNode = chartDom._chartsViews[index]._data.tree._nodes.find(item => {
    return item.name.split('_')[1] == currentEx;
  });

  if(curNode) {
    const depth = curNode.depth;
    const curIsExpand = curNode.isExpand;
    chartDom._chartsViews[index]._data.tree._nodes.forEach(item => {
      if(item.depth == depth && item.name.split('_')[1] != currentEx) {
        item.isExpand = false;

        let inx = nodeArrEx[index].dataIndex.indexOf(item.name);
        if(inx >= 0) {
          nodeArrEx[index].dataIndex.splice(inx, 1);
        }
      }
    });

    let dIndex = nodeArrEx[index].dataIndex.indexOf(curNode.name);
    if(dIndex == -1) {
      nodeArrEx[index].dataIndex.push(curNode.name);
    } else {
      nodeArrEx[index].dataIndex.splice(dIndex, 1);
      setNodeClosed(curNode, index);
    }
  }

  isReadyData = true;
}

// 可多节点展开
const rememberNode = (chartDom, currentEx, index) => {
  const curNode = chartDom._chartsViews[index]._data.tree._nodes.find(item => {
    return item.name.split('_')[1] == currentEx;
  });

  // 如果没有子节点,则不处理
  if(!curNode.children || curNode.children.length == 0) {
    isReadyData = true;
    return
  }

  if(curNode) {
    let dIndex = nodeArrEx[index].dataIndex.indexOf(curNode.name);
    if(dIndex == -1) {
      nodeArrEx[index].dataIndex.push(curNode.name);
    } else {
      nodeArrEx[index].dataIndex.splice(dIndex, 1);
      setNodeClosed(curNode, index);
    }
  }

  isReadyData = true;
}

// 闭合时关闭子集
const setNodeClosed = (treeNode, index) => {
  if(treeNode && treeNode.children) {
    treeNode.children.forEach(item => {

      let inx = nodeArrEx[index].dataIndex.indexOf(item.name);
      if(inx > -1) {
        nodeArrEx[index].dataIndex.splice(inx, 1);
        item.isExpand = false;
      }

      setNodeClosed(item, index);
    })
  }
}

const setNodeCollapsed = (data, nodeObj) => {
  if(data.children && data.children.length > 0) {
    for(let i in data.children) {
      if(nodeObj.dataIndex.includes(data.children[i].name) || nodeObj.dataIndex.includes(data.children[i].name + '')) {
        data.children[i].collapsed = false;
      }
      if(data.children[i].children && data.children[i].children.length > 0) {
        setNodeCollapsed(data.children[i], nodeObj);
      }
    }
  }
}


export default {
  creanTime: () => {
    clearInterval(timeout);
  },

  getDataReady: () => {
    return isReadyData;
  },

  treeEchart: function (id, dataList, rightClick, closeMenu) {
    let pdx = require('@/assets/icon/pdx.png');
    let czKg = require('@/assets/icon/czKg.png');
    let ktKg = require('@/assets/icon/ktKg.png');
    let zmKg = require('@/assets/icon/zmKg.png');
    let ysj = require('@/assets/icon/ysj.png');
    let xyj = require('@/assets/icon/xyj.png');
    let otherKg = require('@/assets/icon/otherKg.png');

    let src1 = require('@/assets/icon/peidianxiang.png');
    let src2 = require('@/assets/icon/duanluqi.png');
    let src = id.indexOf('ptree') != -1 ? src2 : src1

    let tWidth = document.getElementById("tree").clientWidth - 20;
    let blTotal = 0;
    let leftIndex = 0;

    dataList.forEach(item => {
      let ctotal = 0;
      item.leftIndex = blTotal == 0 ? blTotal : blTotal - 1;
      if(item.children) {
        item.children.forEach(child => {
          blTotal += (child.children && child.children.length > 0 ? child.children.length : 1);
          ctotal += (child.children && child.children.length > 0 ? child.children.length : 1);
        })
      } else {
        blTotal += 1;
        ctotal += 1;
      }
      item.widthFlag = ctotal;
    })

    let seriesList = dataList.map((data, dIndex) => {
      let index = nodeArrEx.findIndex(item => {
        return item.chartIndex == dIndex;
      })

      if(index >= 0 && data) {
        if(nodeArrEx[index].dataIndex.length > 0) {
          setNodeCollapsed(data, nodeArrEx[index]);
        } else {
          data.collapsed = true;
        }
      }

      return {
        type: 'tree',
        orient: 'vertical',
        name: data.name,
        edgeShape: "curve",//"polyline", //链接线是折现还是曲线
        data: [data],
        // width: (100 / dataList.length) + '%', //树形图宽(每个树一样宽)
        width: (90 / blTotal * data.widthFlag) + '%', //树形图宽
        top: '20%',
        // left: 10 + (dIndex * tWidth / dataList.length),(每个树一样宽)
        left: 20 + ((data.leftIndex) * tWidth / blTotal),
        symbolSize: [30, 30], //设置自己选择区域的宽高
        symbol: 'rect', //子级选择区域的形状默认circle(圆形),rect矩形
        roam: true, //鼠标移到区块时会显示一个灰色背景的title，移动不同区域时是否开启滑动动画
        initialTreeDepth: nodeArrEx[index] && nodeArrEx[index].dataIndex && nodeArrEx[index].dataIndex.length <= 2 ? nodeArrEx[index].dataIndex.length : 2,  //默认展开层数
        itemStyle: {
          //symbol的样式
          color: '#333',
          borderColor: '#333',
        },
        label: {
          position: [15, 15],
          verticalAlign: 'middle',
          align: 'center',
          color: 'transparent',
          width: 66,
          height: 66,
          backgroundColor: {
            image: src
          }
        },
        leaves: {
          label: {
            position: [15, 15],
            verticalAlign: 'middle',
            align: 'center',
            width: 66,
            height: 66,
            backgroundColor: {
              image: src,
            },
          },
        },
        lineStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'red', // 0% 处的颜色
            }, {
              offset: 1,
              color: 'blue', // 100% 处的颜色
            }],
            global: false, // 缺省为 false
          },
        },
        expandAndCollapse: true,
        animationDuration: 550,
        animationDurationUpdate: 750,
      }
    });

    let option = {
      tooltip: {
        show: 'true',
        trigger: 'item',
        formatter: function (params, ticket, callback) {
          if(params.data.deviceCode != currentCode) {
            currentCode = params.data.deviceCode;
            objInfo = params.data.info;

            currenTip = '<div style="color: #6ca7b4;line-height: 30px; padding: 10px 16px;">';
            objInfo.forEach(item => {
              currenTip += "<div>" + item.name + "：" + item.value + "</div>";
            })
            currenTip += "</div>";

            getOneParValue({devcCode: currentCode}).then(res => {
              if(res.status == 200 && res.object && res.object[0].deviceCode == currentCode) {
                objInfo = objInfo.concat(res.object);
              }

              currenTip = '<div style="color: #6ca7b4;line-height: 30px; padding: 10px 16px;">';
              objInfo.forEach(item => {
                currenTip += "<div>" + item.name + "：" + item.value + "</div>";
              })
              currenTip += "</div>";

              callback(ticket, currenTip);
            });

            return currenTip;
          } else {
            return currenTip;
          }
        },
        backgroundColor: '#235056',
        borderWidth: 0,
        padding: 0,
        extraCssText: 'border-radius: 10px;box-shadow: 0px 0px 27px 0px rgba(154,200,233,0.22) inset, 0px 0px 5.2px 0px #6ca7b4;'
      },
      series: seriesList
    };

    let chartDom = echarts.getInstanceByDom(document.getElementById(id))
    if (chartDom == undefined) {
      chartDom = echarts.init(document.getElementById(id));
      chartDom.setOption(option);

      // 初始化nodeArrEx对象
      dataList.forEach((data, dIndex) => {
        nodeArrEx.push({
          chartIndex: dIndex,
          dataIndex: ['0_1'],
        })
        if(data.children && data.children.length > 0) {
          for(let k = 0; k < data.children.length; k++) {
            if(data.children[k].children && data.children[k].children.length > 0) {
              nodeArrEx[nodeArrEx.length -1].dataIndex.push('1_' + (k + 2));
            }
          }
        }
      })

      let isDragging = false; //是否在拖动节点
      let tiemout = -1;

      // 展开点击节点,并关闭其它同级节点
      chartDom.on('mouseup', (e) => {
        clearTimeout(tiemout);

        if (e.event.which === 1) {
          // 左键关闭菜单
          closeMenu && closeMenu();
        }
        if (e.event.which === 3) {
          // 可以在这里阻止默认行为，防止右键弹出默认菜单
          return event.preventDefault();
        }

        if (!isDragging) {
          const currentEx = e.data.flag;
          let index = nodeArrEx.findIndex(item => {
            return item.chartIndex == e.seriesIndex;
          })
          // resetNode(chartDom, currentEx, index);
          rememberNode(chartDom, currentEx, index);
        }

        isDragging = false;
      })

      chartDom.on('mousemove', (e) => {
        isDragging = true;
        isReadyData = true;
      })

      // 绑定 mousemove 事件
      chartDom.on('mousedown', function (params) {
        isDragging = false;
        isReadyData = false;
      });

      chartDom.on('contextmenu', rightClick) // 右键事件
    } else {
      chartDom.setOption(option);
    }

    window.addEventListener('resize', () => {
      chartDom.resize()
    })
    let erd = elementResizeDetectorMaker();
    erd.listenTo(document.getElementById(id), function (element) {
      chartDom.resize()
    })

    // 阻止右键默认的菜单弹出
    document.oncontextmenu = function(param) {
      return false
    }
    return chartDom
  },
}
